﻿#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//main76&77：指针操作野指针和取数组值
int main76()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int* p = arr;
	p++;
	*p = 100;//arr[1]=100; --->{ 1,100,3,4,5,6,7,8,9,10 };

	//1.野指针;
	p = 100;
	//2.非法操作野指针内存；
	//*p = 100;

	p = &arr[9];
	*p = 200;//arr[9]=200; --->{ 1,100,3,4,5,6,7,8,9,200 };

	p--;
	*p = 300;//arr[8]=300; --->{ 1,100,3,4,5,6,7,8,300,200 };

	p = &arr[0];
	*p += 400;//arr[0]=401; --->{ 401,100,3,4,5,6,7,8,300,200 };

	printf("4.arr[0]的地址，即数组arr的首地址，或者说p的地址：%d\n", p);//17824264
	//6.前后差值为400，为4*100；
	p += 100;
	printf("5.p的地址增加了100个int的大小的地址：%d\n", p);//17824664

	//8.相同类型int的地址相减，结果还是同类型int的倍数；400/4=100；
	int result = p - arr;
	printf("7.输出p的地址-arr的首地址，结果为：%d\n", result);//100

	for (int i = 0; i < 10; i++)
	{
		printf("3.输出通过指针p改变数组arr后，数组arr[i]的值：%d\n", arr[i]);//401,100,3,4,5,6,7,8,300,200
	}

	system("pause");
	return EXIT_SUCCESS;
}
int main77(void)
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int* p = arr;
	p = &arr[9];
	int result = &arr[9] - &arr[0];
	printf("9.输出&arr[9]-&arr[0]的结果：%d\n", result);//9

	int retPointer = p - arr;
	printf("10.输出指针地址p为arr[9]，与arr首地址的差值：%d\n", retPointer);//9

	int* pArr;
	for (pArr = arr; pArr <= &arr[9]; pArr++)
	{
		printf("11.用*pArr来取数组arr的值，每次指针pArr地址加一个int类型的值，指向下一个元素：%d\n", *pArr);//1 2 ... 9 10
		//13.每次加一个int，即加4；
		printf("12.输出当前指针pArr的地址：%d\n", pArr);//17824352 17824356 ... 17824376 17824380
		//15.每次都获取的是指向地址的元素；
		printf("14.用指针索引pArr[0]来取数组arr的值：%d\n", pArr[0]);//1 2 .. 9 10
	}

	return 0;
}